package com.mt.fpb.Scheduled;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.mapper.*;
import com.mt.fpb.model.TransactionRecords;
import com.mt.fpb.model.WxProduct;
import com.mt.fpb.model.WxProductOrder;
import com.mt.fpb.utils.Constants;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Configuration
@EnableScheduling
@Transactional(rollbackFor={Exception.class})
public class OrderScheduled {

    @Autowired
    private WxProductMapper wxProductMapper;

    @Autowired
    private WxProductOrderMapper productOrderMapper;

    @Autowired
    private BalanceMapper balanceMapper;

    @Autowired
    private RxEmployeeMapper rxEmployeeMapper;

    @Autowired
    private TransactionRecordsMapper transactionRecordsMapper;

    //客户点击了提前赎回按钮，30天后才可以赎回，数据库会存储赎回到账时间，
    // 会每天00:02计算当前时间是否超过赎回到账时间，超过，则改变订单状态
    //@Scheduled(cron = "0 0 12 * * ?")
    @Scheduled(cron = "*/5 * * * * ?") //暂时用5秒测试
    public void updateOrderStatus() {
        //查询出所有提前赎回状态的客户
        QueryWrapper<WxProductOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", Constants.IN_EARLY_REDEMPTION);
        List<WxProductOrder> wxProductOrders = productOrderMapper.selectList(wrapper);
        //遍历出每个订单的赎回到账时间，当前时间大于赎回到账时间的话，将订单状态变为5,提前赎回状态
        try {
            for (WxProductOrder wxProductOrder : wxProductOrders) {
                Date currentTime = new Date(); //当前时间
                Date endTime = wxProductOrder.getEndTime(); //赎回到账时间
                if (endTime != null &&currentTime.after(endTime)) {
                    //1 进行订单状态更改
                    wxProductOrder.setOrderStatus(Constants.EARLY_REDEMPTION);
                    int updateStatus = productOrderMapper.updateById(wxProductOrder);
                    if (updateStatus > 0) {
                        log.info("订单id为" + wxProductOrder.getId() + "已达到赎回到账时间，状态已经更改");
                        //2 将这条数据插入或者更新到余额表中
                        saveOrUpdateBalance(wxProductOrder);
                        //3 将这条数据插入到交易记录表
                        saveTransactionRecords(wxProductOrder);
                    }else {
                        log.error("订单id为" + wxProductOrder.getId() + "更新状态出错，请查看具体日志", wxProductOrder);
                    }
                }
            }
        }catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("定时任务updateOrderStatus出错，请及时查看日志信息", e);
        }
    }

    //更新或者插入余额表
    private void saveOrUpdateBalance(WxProductOrder wxProductOrder) throws Exception {
        //1 根据订单表的人员id，到人员表中找到名字和身份证
        log.info("根据订单表的人员id" + wxProductOrder.getEmployeeId() + "到人员表中找到名字和身份证");
        Map<String, Object> nameAndIdCard = rxEmployeeMapper.getNameAndIdCardById(wxProductOrder.getEmployeeId());
        //2 根据名字和身份证去找余额表中是否有这个人的信息
        String name = (String) nameAndIdCard.get("name");
        String idCard = (String) nameAndIdCard.get("id_card");
        float orderMoney = wxProductOrder.getOrderMoney();
        Map<String, Object> balanceMap = balanceMapper.selectBalance(name, idCard);
        if (MapUtil.isEmpty(balanceMap)) {
            //3 余额表中没有这个人的信息进行insert操作
            log.info("余额表中没有这个人的信息进行insert操作");
            balanceMapper.insertInfo(name, idCard, orderMoney);
        } else {
            //3 余额表中有这个人信息进行update 余额的操作
            log.info("余额表中有这个人信息进行update 余额的操作");
            float personalBalance = (float) balanceMap.get("personal_balance") + orderMoney;
            balanceMapper.updateInfo(name, idCard, personalBalance);
        }
    }

        //插入信息到交易记录表
        private void saveTransactionRecords(WxProductOrder wxProductOrder) throws Exception{
            log.info("提前赎回操作插入到交易记录表中");
            WxProduct wxProduct = wxProductMapper.getProductByProductId(wxProductOrder.getProductId());
            TransactionRecords transactionRecords = new TransactionRecords();
            //提前赎回插入
            transactionRecords.setEmployeeId(wxProductOrder.getEmployeeId());
            transactionRecords.setProductName(wxProduct.getProductName());
            transactionRecords.setPayMoney(wxProductOrder.getPayMoney());
            transactionRecords.setStartTime(wxProductOrder.getStartTime());
            transactionRecords.setEndTime(wxProductOrder.getEndTime());
            transactionRecords.setInterest(wxProductOrder.getOrderMoney() - wxProductOrder.getPayMoney());
            transactionRecords.setOrderStatus(Constants.EARLY_REDEMPTION_TRANSACTION);
            transactionRecords.setTransactionAmount(wxProductOrder.getOrderMoney());
            transactionRecordsMapper.insert(transactionRecords);
        }
}
